package cn.iune.backcenter.authen;

import java.sql.Timestamp;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.alibaba.fastjson.JSONObject;
import com.justep.baas.Utils;


@Transactional
@Service
public class AuthenticationServiceImpl implements IAuthenticationService {
	
	@Autowired
	private ISaOppersonService saOppersonService;
	
	@Autowired
	private ISaRelationalLoginService saRelationalLoginService;

	public AuthenticationServiceImpl() {
		System.out.println("AuthenticationServiceImpl-->>...");
	}

	/*
	//用户名和密码登录
	//JWT登录，产生token
	@Transactional
	@Override
	public JSONObject login(String username, String password, boolean rememberMe, String redirectUrl, String subject, String secretkey) {
		//首先判断类型
		boolean isEmail = LoginUtils.isEmail(username);
		boolean isPhone = LoginUtils.isPhoneLegal(username);
		if(isEmail || isPhone){
			//电子邮件或者手机号
			SaRelationalLogin saRelationalLogin = saRelationalLoginService.getByNo(username);
			if(saRelationalLogin==null) {
				String info = "用户名或者密码不正确";
				return this.loginFailure(info);				
			}else {
				//记录存在
				String personID = saRelationalLogin.getPersonID();
				//打包token及返回数据
				SaOpperson person = saOppersonService.getByID(personID);
				if(person!=null){
					//核对密码
					if(password.toUpperCase().equals(person.getsPassword())) {
						return this.loginSuccess(person, redirectUrl, subject, secretkey);
					}else {
						String info = "用户名或者密码不正确";
						return this.loginFailure(info);				
					}
				}else{
					//用户不存在或者密码不正确
					String info = "用户主数据不存在，请联系系统管理员。";
					return this.loginFailure(info);
				}
			}
		}else {
			//验证用户名和密码
			SaOpperson person = this.getByUsername(username);
			//核对密码
			if(person!=null && person.getsPassword().equals(password.toUpperCase())){
				return this.loginSuccess(person, redirectUrl, subject, secretkey);
			}else {
				String info = "用户名或者密码不正确";
				return this.loginFailure(info);
			}
		}
		
	}
	
	//用户名和密码登录
	//JWT登录，产生token
	@Transactional
	@Override
	public JSONObject login(String username, String password) {

		//首先判断类型
		boolean isEmail = LoginUtils.isEmail(username);
		boolean isPhone = LoginUtils.isPhoneLegal(username);
		if(isEmail || isPhone){
			//电子邮件或者手机号
			SaRelationalLogin saRelationalLogin = saRelationalLoginService.getByNo(username);
			if(saRelationalLogin==null) {
				String info = "用户名或者密码不正确";
				return this.loginFailure(info);				
			}else {
				//记录存在
				String personID = saRelationalLogin.getPersonID();
				//打包token及返回数据
				SaOpperson person = saOppersonService.getByID(personID);
				if(person!=null){
					//核对密码
					if(password.toUpperCase().equals(person.getsPassword())) {
						return this.loginSuccess(person);
					}else {
						String info = "用户名或者密码不正确";
						return this.loginFailure(info);				
					}
				}else{
					//用户不存在或者密码不正确
					String info = "用户主数据不存在，请联系系统管理员。";
					return this.loginFailure(info);
				}
			}
		}else {
			//验证用户名和密码
			SaOpperson person = this.getByUsername(username);
			//核对密码
			if(person!=null && person.getsPassword().equals(password.toUpperCase())){
				return this.loginSuccess(person);
			}else {
				String info = "用户名或者密码不正确";
				return this.loginFailure(info);
			}
		}
		
	}
	

	//验证码登录，用户不存在就新增（只能是手机号或者是电子邮件）
	//JWT登录，产生token
	@Transactional
	@Override
	public JSONObject vogin(String emailphone, String validcode, boolean rememberMe, String redirectUrl, String subject, String secretkey) {

		//首先判断类型
		boolean isEmail = LoginUtils.isEmail(emailphone);
		boolean isPhone = LoginUtils.isPhoneLegal(emailphone);
		if(isEmail || isPhone){
			//电子邮件或者手机号
			SaRelationalLogin saRelationalLogin = saRelationalLoginService.getByNo(emailphone);
			if(saRelationalLogin==null) {
				//记录不存在，新建（注册）！
				SaOpperson person = null;

				if(person==null) {
					String info = "不是电子邮件也不是手机号，不能登录！";
					return this.loginFailure(info);
				}
				
				saRelationalLogin = new SaRelationalLogin();
				saRelationalLogin.setsID(Utils.getUUID());
				
				saRelationalLogin.setPersonID(person.getsID());
				
				saRelationalLogin.setIdentification(emailphone);
				saRelationalLogin.setValidCode(null);
				saRelationalLogin.setsValidState(1);
				saRelationalLogin.setRegisterDate(new Timestamp(System.currentTimeMillis()));
				saRelationalLogin.setVersion(0);
				
				saRelationalLoginService.insert(saRelationalLogin);
				
				return this.loginSuccess(person, redirectUrl, subject, secretkey);
				
			}else {
				//记录存在
				String personID = saRelationalLogin.getPersonID();
				//打包token及返回数据
				SaOpperson person = saOppersonService.getByID(personID);
				if(person!=null){
					return this.loginSuccess(person, redirectUrl, subject, secretkey);
				}else{
					//用户不存在或者密码不正确
					String info = "用户主数据不存在，请联系系统管理员。";
					return this.loginFailure(info);
				}
			}
		}else {
			String info = "不是电子邮件也不是手机号，不能登录！";
			return this.loginFailure(info);
		}

	}
	*/

	/*
	private JSONObject loginSuccess(SaOpperson person, String redirectUrl, String subject, String secretkey) {

		//打包token及返回数据
		//登录成功
    	JSONObject tokenData = new JSONObject();
    	tokenData.put("sLoginName", person.getsLoginName());
    	tokenData.put("userId", person.getsID());
    	tokenData.put("cUsercode", person.getsCode());
    	tokenData.put("cUsername", person.getsName());
    	tokenData.put("images", person.getImages());

		//生成token
    	String token = myJWT.buildJwt(subject, secretkey, tokenData);
    	
    	JSONObject json = new JSONObject();
    	json.put("code", 0);
    	json.put("status", "成功");
    	json.put("redirectUrl", redirectUrl);
    	json.put("sLoginName", person.getsLoginName());
    	json.put("cUsername", person.getsName());
//	    json.put("images", person.getImages());
        
    	json.put("token", token);
		
    	return json;
	}

	private JSONObject loginSuccess(SaOpperson person) {

		//打包token及返回数据
		//登录成功
    	JSONObject json = new JSONObject();
    	json.put("sLoginName", person.getsLoginName());
    	json.put("userId", person.getsID());
    	json.put("cUsercode", person.getsCode());
    	json.put("cUsername", person.getsName());
    	json.put("images", person.getImages());
		
    	return json;
	}

	private JSONObject loginFailure(String info) {
    	JSONObject json = new JSONObject();
    	json.put("code", -1);
    	json.put("msg", "failure");
    	json.put("status", "失败");
    	json.put("info", info);
		
    	return json;
	}
	*/


	//用登录名和密码注册（这个不再使用，改为使用手机号和电子邮件注册）
	@Transactional
	@Override
	public SaOpperson register(String sLoginName, String password) {  
		long now = System.currentTimeMillis();

		SaOpperson person = new SaOpperson();
		String sID = String.valueOf(System.nanoTime());//Utils.getUUID();
		person.setsID(sID);
		person.setsLoginName(sLoginName);
		person.setsPassword(password);
		person.setsCode(String.valueOf(System.nanoTime()));
		person.setsName("您的称呼");
		person.setsCreatorFID(sID);
		person.setCreateDate(new Timestamp(now));
		person.setRegisterDate(new Timestamp(now));
		person.setsMailState(-1);
		person.setsMobileState(-1);
		
		person.setsMainOrgID(sID);//所属公司，当接受别的公司邀请后，会变更为别的公司ID
		
		
		//判断是否用户名为电子邮件格式
//		boolean isEmail = LoginUtilsService.isEmail(sLoginName);
//		boolean isPhone = LoginUtilsService.isPhoneLegal(sLoginName);
//		if(isEmail){
//			//是电子邮件格式
//			person.setsMail(sLoginName);
//			person.setsMailState(1);
//		}
//		if(isPhone){
//			//是电子邮件格式
//			person.setsMobilePhone(sLoginName);
//			person.setsMobileState(1);
//		}
		
		saOppersonService.insert(person);
		
		return person;
	}
	
	@Transactional
	@Override
	public SaOpperson register(String identification, String password, String sType) {  
		long now = System.currentTimeMillis();
		//生成密码
		//123456
		//String password = "E10ADC3949BA59ABBE56E057F20F883E";
		//生成随机密码
		//String password = UserSystemService.randomPassword();
		
		SaOpperson person = new SaOpperson();
		String sID = String.valueOf(System.nanoTime());//Utils.getUUID();
		person.setsID(sID);
		person.setsLoginName(sID);
		person.setsPassword(password);
		person.setsCode(String.valueOf(System.currentTimeMillis()));
		person.setsName("您的称呼");
		person.setsCreatorFID(sID);
		person.setCreateDate(new Timestamp(now));
		person.setRegisterDate(new Timestamp(now));
//		person.setsMailState(1);
//		person.setsMail(identification);
//		person.setsMobileState(-1);
		
		person.setsMainOrgID(sID);//所属公司，当接受别的公司邀请后，会变更为别的公司ID

		if("EMAIL".equals(sType)) {
			//是电子邮件格式
			person.setsMail(identification);
			person.setsMailState(1);
		}
		if("PHONE".equals(sType)) {
			//是电子邮件格式
			person.setsMobilePhone(identification);
			person.setsMobileState(1);
		}
		
		saOppersonService.insert(person);
		
		if(sType==null) {
			return person;
		}
		
		//从表
		SaRelationalLogin saRelationalLogin = new SaRelationalLogin();
		saRelationalLogin.setsID(Utils.getUUID());
		
		saRelationalLogin.setPersonID(person.getsID());
		
		saRelationalLogin.setIdentification(identification);
		saRelationalLogin.setsType(sType);
		saRelationalLogin.setValidCode(null);
		saRelationalLogin.setsValidState(1);
		saRelationalLogin.setRegisterDate(new Timestamp(System.currentTimeMillis()));
		saRelationalLogin.setVersion(0);
		
		saRelationalLoginService.insert(saRelationalLogin);
		
		return person;
	}

	
	//绑定手机或者电子邮件
	@Override
	@Transactional
	public JSONObject binding(String personID, String identification, String sType) {  
		JSONObject json = new JSONObject();
		
		// 创建一个用户
		SaRelationalLogin saRelationalLogin = new SaRelationalLogin();
		//新增手机或者是电子邮件的绑定记录
		SaOpperson person = saOppersonService.getByID(personID);
		if(person==null) {
			json.put("code", -1);
			json.put("msg", "failure");
			json.put("info", "用户记录不存在！");
			return json;
		}
		
		saRelationalLogin = new SaRelationalLogin();
		saRelationalLogin.setsID(Utils.getUUID());
		
		saRelationalLogin.setPersonID(person.getsID());
		
		saRelationalLogin.setIdentification(identification);
		saRelationalLogin.setsType(sType);
		saRelationalLogin.setValidCode(null);
		saRelationalLogin.setsValidState(1);
		saRelationalLogin.setRegisterDate(new Timestamp(System.currentTimeMillis()));
		saRelationalLogin.setVersion(0);
		
		saRelationalLoginService.insert(saRelationalLogin);
		
		json.put("code", 0);
		json.put("msg", "success");
		return json;
	}
	
	@Transactional
	@Override
	public SaOpperson getByUsername(String username) {
		SaOpperson person = null;
		if(LoginUtils.isEmail(username)) {
			//email
			//person = saOppersonService.getByMail(username);
			SaRelationalLogin saRelationalLogin = saRelationalLoginService.getByNo(username);
			if(saRelationalLogin==null) {
				return null;
			}else {
				String personID = saRelationalLogin.getPersonID();
				person = saOppersonService.getByID(personID);
			}
			
		}else if(LoginUtils.isPhoneLegal(username)) {
			//phone
			//person = saOppersonService.getByMobilePhone(username);
			SaRelationalLogin saRelationalLogin = saRelationalLoginService.getByNo(username);
			if(saRelationalLogin==null) {
				return null;
			}else {
				String personID = saRelationalLogin.getPersonID();
				person = saOppersonService.getByID(personID);
			}
		}else {
			//sLoginName
			person = saOppersonService.getByLoginName(username);
		}
		return person;
	}
	
	//修改密码
	@Transactional
	@Override
	public JSONObject updatePwd(String username, String password) {  
		SaOpperson person = this.getByUsername(username);
		if(person==null) {
			JSONObject json = new JSONObject();
			json.put("code", -1);
			json.put("msg", "failure");
			json.put("info", "失败！");
			return json;
		}else {
			person.setsPassword(password);
			
			//更新用户
			saOppersonService.update(person);
			JSONObject json = new JSONObject();
			json.put("code", 0);
			json.put("msg", "success");
			json.put("info", "成功！");
			return json;
		}
		
	}

	
	
	

	
}
